const express = require('express');
const router = express.Router();
const { pool } = require('../config/db');
const auth = require('../middleware/auth');

// 获取成绩列表
router.get('/', auth, async (req, res) => {
  try {
    // 学生只能查看自己的成绩
    if (req.user.role === 'student') {
      const [scores] = await pool.query('SELECT * FROM scores WHERE studentId = ? AND isPublished = TRUE', [req.user.id]);
      return res.json(scores);
    }
    
    // 教师只能查看自己教授课程的成绩
    if (req.user.role === 'teacher') {
      const [scores] = await pool.query(`
        SELECT s.* FROM scores s
        JOIN courses c ON s.courseId = c.id
        WHERE c.teacherId = ?
      `, [req.user.id]);
      return res.json(scores);
    }
    
    // 管理员和辅导员可以查看所有成绩
    const [scores] = await pool.query('SELECT * FROM scores');
    res.json(scores);
  } catch (error) {
    console.error('获取成绩列表失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 获取单个成绩信息
router.get('/:id', auth, async (req, res) => {
  try {
    const scoreId = req.params.id;
    const [rows] = await pool.query('SELECT * FROM scores WHERE id = ?', [scoreId]);
    
    if (rows.length === 0) {
      return res.status(404).json({ message: '成绩记录不存在' });
    }
    
    // 检查权限
    if (req.user.role === 'student' && (rows[0].studentId !== req.user.id || !rows[0].isPublished)) {
      return res.status(403).json({ message: '权限不足' });
    }
    
    res.json(rows[0]);
  } catch (error) {
    console.error('获取成绩信息失败:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router;